package com.hujh.android;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.hujh.android.bean.ItemAdapter;
import com.hujh.android.bean.ItemInfo;

public class ListViewPageActivity extends Activity implements OnScrollListener,OnItemClickListener {

	private List<ItemInfo> itemInfoList;

	private List<ItemInfo> itemInfoListTemp;

	private ItemAdapter itemAdapter;

	private ListView listView;

	private LinearLayout loading;

	private Handler handler;

	private boolean refreshable;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		init();
		updateApplicationItemInfoList();
	}

	private void init() {
		setContentView(R.layout.activity_listview);
		listView = (ListView) findViewById(R.id.list);
		loading = (LinearLayout) findViewById(R.id.loading);

		itemInfoList = new ArrayList<ItemInfo>();
		itemAdapter = new ItemAdapter(this,itemInfoList);
		handler = createHandler();
		refreshable = true;

		listView.setAdapter(itemAdapter);
		listView.setOnItemClickListener(this);
		listView.setOnScrollListener(this);
	}

	private Handler createHandler() {
		Handler handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {
				case 1:
					if (itemInfoListTemp != null) {
						ListViewPageActivity.this.itemInfoList.addAll(itemInfoListTemp);
						ListViewPageActivity.this.itemAdapter.notifyDataSetChanged();
						ListViewPageActivity.this.loading.setVisibility(View.GONE);
						ListViewPageActivity.this.refreshable = true;
					} else {
						ListViewPageActivity.this.loading.setVisibility(View.GONE);
						Toast.makeText(ListViewPageActivity.this,"All of applications have been shown!",Toast.LENGTH_LONG).show();
					}
					break;
				default:
					break;
				}
			}
		};
		return handler;
	}

	public Handler getHandler() {
		return handler;
	}

	private void updateApplicationItemInfoList() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub

				if (ListViewPageActivity.this.itemInfoList.size() < 80) {
					ListViewPageActivity.this.itemInfoListTemp = ListViewPageActivity.this.getLocalApplicationInfo();
				} else {
					ListViewPageActivity.this.itemInfoListTemp = null;
				}

				try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				Message message = new Message();
				message.what = 1;
				ListViewPageActivity.this.getHandler().sendMessage(message);
			}

		}).start();
	}

	private ArrayList<ItemInfo> getLocalApplicationInfo() {

		PackageManager packageManager = this.getPackageManager();
		ArrayList<ItemInfo> applicationItemInfoList = new ArrayList<ItemInfo>();
		List<PackageInfo> packageInfoList = packageManager.getInstalledPackages(0);

		for (int i = packageInfoList.size(); i > 0; i--) {

			ApplicationInfo applicationInfo = packageInfoList.get(i - 1).applicationInfo;

			if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
				try {
					ItemInfo applicationItemInfo = new ItemInfo();

					String packageName = packageInfoList.get(i - 1).packageName;
					String[] permissions = packageManager.getPackageInfo(
							packageName, PackageManager.GET_PERMISSIONS).requestedPermissions;

					applicationItemInfo.setPackageName(packageName);
					applicationItemInfo.setPermissions(permissions);

					applicationItemInfo.setIcon(packageManager
							.getApplicationIcon(applicationInfo));
					applicationItemInfo.setName(packageManager
							.getApplicationLabel(applicationInfo).toString());

					applicationItemInfoList.add(applicationItemInfo);

				} catch (NameNotFoundException e) {
					// TODO Auto-generated catch block
				}
			}
		}
		if ((!applicationItemInfoList.isEmpty()) && (applicationItemInfoList.size() < 10)) {
			for (int i = applicationItemInfoList.size(); i < 10; i++) {
				applicationItemInfoList.add(applicationItemInfoList.get(9 - i));
			}
		}
		return applicationItemInfoList;
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub
		if ((firstVisibleItem + visibleItemCount == totalItemCount) && (totalItemCount != 0)) {
			if (refreshable) {
				refreshable = false;
				loading.setVisibility(View.VISIBLE);
				updateApplicationItemInfoList();
			}
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position,long id) {
		// TODO Auto-generated method stub
		AlertDialog.Builder permissionDialog = new AlertDialog.Builder(this);
		permissionDialog.setIcon(itemInfoList.get(position)
				.getIcon());
		permissionDialog.setTitle(itemInfoList.get(position)
				.getName());
		String[] permissions = itemInfoList.get(position)
				.getPermissions();

		StringBuffer temp = new StringBuffer();
		if (permissions != null) {
			for (int i = 0; i < permissions.length; i++) {
				temp.append(permissions[i]);
				temp.append("\n");
			}
		} else {
			temp.append("permission is null");
		}
		permissionDialog.setMessage(temp.toString());
		permissionDialog.setPositiveButton("OK",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.cancel();
					}
				});
		permissionDialog.create().show();
	}

}
